package 线程同步.方法三_Lock锁;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Account {
    private double money; // 余额
    private String cardId;

    // 创建了一个锁对象
    private final Lock lk = new ReentrantLock();

    public Account(String cardId, double money) {
        this.money = money;
        this.cardId = cardId;
    }

    public Account() {
    }

    public double getMoney() {
        return money;
    }

    public void setMoney(double money) {
        this.money = money;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public void drawMoney(double money) {
        // 搞清楚谁在取钱
        String name = Thread.currentThread().getName();
        // 加锁
        try {
            lk.lock();
            // 1. 判断余额是否足够
            if (this.money >= money) {
                System.out.println(name + "取钱" + money + "成功");
                this.money -= money;
                System.out.println("余额剩余: " + this.money);
            } else {
                System.out.println(name + "取钱,余额不足");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 解锁
            lk.unlock(); //防止出现bug不解锁导致出现问题
        }

    }
}
